<?php
// +----------------------------------------------------------------------
// | DCloud [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.yunku.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\controller;

use dc\controller\HomeBaseController;
use dragon\Company\Entity\Company;
use dragon\Company\Entity\CompanyUser;
use dragon\SysConfig;
use dragon\User\User;
use think\Db;
use think\Validate;
use app\user\model\UserModel;

class RegisterController extends HomeBaseController
{

    /**
     * 前台用户注册
     */
    public function index()
    {
        $redirect = $this->request->post("redirect");
        if (empty($redirect)) {
            $redirect = $this->request->server('HTTP_REFERER');
        } else {
            $redirect = base64_decode($redirect);
        }
        session('login_http_referer', $redirect);

        if (dc_is_user_login()) {
            return redirect($this->request->root() . '/');
        } else {
            $this->assign('company_types', Db::name('company_type')->where(['open' => 1])->select());
            return $this->fetch(":register");
        }
    }

    /**
     * 前台用户注册提交
     */
    public function doRegister()
    {
        $rules = [
            'name'  => 'require',
            'organization_code'  => 'require',
            'types'  => 'require',
            'business_license'  => 'require',
            'identity_card'  => 'require',
//            'handle_identity_card'  => 'require',
            'contact_name'  => 'require',
            'contact_mobile'  => 'require',
            'username'  => 'require|unique:user,user_login',
            'captcha'  => 'require',
            'password' => 'require|min:6|max:32',
        ];

        $validate = new Validate($rules);
        $validate->message([
            'name.require'                  => '企业名称不能为空',
            'organization_code.require'     => '社会统一代码不能为空',
            'types.require'                 => '请选择企业类型',
            'business_license.require'      => '请上传营业执照',
            'identity_card.require'         => '请上传注册人身份证照片',
//            'handle_identity_card.require'  => '请上传申请人手持身份证照片',
            'contact_name.require'          => '联系人不能为空',
            'contact_mobile.require'        => '联系电话不能为空',
            'username.require'              => '手机号不能为空',
            'username.unique'              => '手机号已注册，如有疑问请联系客服',
            'password.require' => '密码不能为空',
            'password.max'     => '密码不能超过32个字符',
            'password.min'     => '密码不能小于6个字符',
            'captcha.require'  => '验证码不能为空',
        ]);

        $data = $this->request->post();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $captchaId = empty($data['_captcha_id']) ? '' : $data['_captcha_id'];
        if (!dc_captcha_check($data['captcha'], $captchaId)) {
            $this->error('验证码错误');
        }

        $user['user_pass'] = $data['password'];
        if (Validate::is($data['username'], 'email')) {
            $user['user_email'] = $data['username'];
        } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
            $user['mobile'] = $data['username'];
        }

        try {
            Db::startTrans();

            // 企业注册
            $data['status']  = SysConfig::COMPANY_APPLY;
            $company = Company::create($data);

            $roleId = $company->master_role['id'];

            // 添加企业用户
            $companyUser = new CompanyUser;
            $companyUser->save([
                'company_id'=> $company->id,
                'role_id'   => $roleId,
                'name'      => $data['contact_name'],
                'mobile'    => $data['username'],
                'user_pass' => $data['password'],
            ]);

            $company->save(['user_id' => $companyUser['user_id']]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('注册成功', url('/admin'));
    }
}